package com.chuantou.yuba.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

public class FileUtil {
	public static File getCacheDir() {
		File dir = new File(Environment.getExternalStorageDirectory(), ".yuba");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	public static File getImageCacheDir() {
		File dir = new File(getCacheDir(), ".img");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	public static File getChatCacheDir() {
		File dir = new File(getCacheDir(), ".ccache");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	public static void deleteFiles(List<String> paths) {
		if (paths == null || paths.isEmpty())
			return;
		for (String path : paths) {
			new File(path).delete();
		}
	}

	public static void deleteFile(File file) {
		if (file == null || !file.exists())
			return;
		if (file.isFile()) {
			file.delete();
		} else {
			File[] files = file.listFiles();
			if (files != null && files.length > 0) {
				for (File f : files) {
					deleteFile(f);
				}
			}
			file.delete();
		}
	}

	public static File copyResource2Sd(Context context, int resID) {
		try {
			String imageName = String.valueOf(resID).concat(".png");
			File file = new File(getCacheDir(), imageName);
			if (file.exists())
				return file;
			InputStream is = context.getResources().openRawResource(resID);

			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[8192];
			int count = 0;
			// 开始复制Logo图片文件
			while ((count = is.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
			}
			fos.close();
			is.close();
			return file;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}
		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
}
